package com.bianguo.android.bprinter.view.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import java.util.ArrayList;

public class ZoomViewLayout extends RelativeLayout implements ZoomView.OnFocusListener, ZoomView.OnClickPointListener {

    private ArrayList<ZoomView> zoomViews;

    public ZoomViewLayout(Context context) {
        this(context, null);
    }

    public ZoomViewLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZoomViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        zoomViews = new ArrayList<>();
    }

    public void addZoomView(Bitmap bitmap, boolean fromRes) {
        ZoomView zoomView = new ZoomView(getContext());
        zoomView.addBitmap(bitmap);
        zoomView.setOnFocusListener(this);
        zoomView.setOnClickPointListener(this);
        addView(zoomView);
        zoomViews.add(zoomView);

        if (!fromRes) {
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(dm);
            zoomView.postScale(160 / dm.densityDpi);
        }
    }

    @Override
    public void onFocus(View view) {
        zoomViews.remove(view);
        zoomViews.add(0, (ZoomView) view);
        sortZ();
    }

    @Override
    public void onClickPoint(View view, int pointType) {
        switch (pointType) {
            case ZoomView.CLICK_POINT_TYPE_DELETE:
                zoomViews.remove(view);
                removeView(view);
                sortZ();
                break;
        }
    }

    private void sortZ() {
        int size = zoomViews.size();
        for (int i = 0; i < size; i++) {
            ZoomView zoomView = zoomViews.get(i);
            zoomView.setElevation(size - i);
        }
    }
}
